<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ReleasePolicy extends Model
{

    /**
     * 与模型关联的数据表
     *
     * @var string
     */
    protected $table = 'release_policy';

    /**
     * 该模型是否被自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = false;

    public function addReleasePolicy($data)
    {
        if($id = $this->insertGetId($data)){
            $this->where('id',$id)->update(['rank'=>$id,'updtime'=>time()]);
            return ['code'=>'1','message'=>'添加成功','id'=>$id];
        }else{
            return ['code'=>'1','message'=>'添加失败'];
        }
    }

    public function getReleasePolicy($where)
    {
         $info = $this->where($where)->first();
         $info->type = explode(',',$info->type);
         return $info;
    }

    public function updReleasePolicy($where,$data)
    {
        $bool = $this->where($where)->update($data);
        if($bool){
            return ['code'=>'1','message'=>'修改成功'];
        }else{
            return ['code'=>'0','message'=>'修改失败'];
        }
    }

    public function getReleasePolicyList($where)
    {
        $members = $this
            ->where('status',1)
            ->when(!empty($where['type']),function ($query) use ($where){
                $query->where('type','like','%'.$where['type'].'%');
            })
            ->when(!empty($where['title']),function ($query) use ($where){
                $query->where('title','like','%'.$where['title'].'%');
            })

            //开始时间
            ->when(!empty($where['onset_time']),function ($query) use ($where){
                $onset_time = strtotime($where['onset_time']);
                $query->where('addtime','>',$onset_time);
            })

            //结束时间
            ->when(!empty($where['over_time']),function ($query) use ($where){
                $over_time = strtotime($where['over_time']);
                $query->where('addtime','<',$over_time);
            })

            ->orderBy('rank','asc')

            ->select([
                'id',
                'type',
                'title',
                'fb_user',
                'status',
                'img',
                'addtime',
            ])
            ->paginate($where['page_size']);


        $adminModel = new Admin();
        foreach ($members as $key=>$value){

            $members[$key]->type = explode(',',$value->type);
            $members[$key]->addtime = date('Y-m-d H:i:s',$value->addtime);
            if(empty($value->fb_user)){
                $members[$key]->fb_user = '';
            }else{
                $admin = $adminModel->getAdmin(['id'=>$value->fb_user],['name']);
                $members[$key]->fb_user = $admin->name;
            }
        }

        return $members;
    }

}
